import { 
  Controller, 
  Post, 
  Get, 
  Delete,
  UseInterceptors, 
  UploadedFile, 
  UploadedFiles,
  Body,
  Param,
  Query,
  BadRequestException
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiOperation, ApiResponse, ApiConsumes, ApiBearerAuth } from '@nestjs/swagger';
import { Roles, CurrentUser } from '@app/auth';
import { UploadProxyService } from '../services/upload-proxy.service';
import { Request } from 'express';
import { Req } from '@nestjs/common';

// DTOs for file upload
class UploadConfigDto {
  maxFileSize?: number;
  allowedTypes?: string[];
  uploadPath?: string;
  enableThumbnail?: boolean;
  thumbnailSizes?: Array<{ width: number; height: number; name: string }>;
}

class MediaQueryDto {
  page?: number = 1;
  limit?: number = 20;
  type?: 'image' | 'video' | 'audio' | 'document';
  search?: string;
  startDate?: string;
  endDate?: string;
  sortBy?: string = 'createdAt';
  sortOrder?: 'ASC' | 'DESC' = 'DESC';
}

@ApiTags('文件上传')
@ApiBearerAuth()
@Controller('admin/upload')
export class UploadController {
  constructor(private readonly uploader: UploadProxyService) {}

  @Post('image')
  @ApiOperation({ summary: '上传单张图片' })
  @ApiConsumes('multipart/form-data')
  @ApiResponse({ status: 200, description: '图片上传成功' })
  @UseInterceptors(FileInterceptor('file'))
  @Roles('admin', 'editor', 'author')
  async uploadImage(
    @UploadedFile() file: Express.Multer.File,
    @Body() body: { alt?: string; title?: string },
    @CurrentUser() user: any,
    @Req() req: Request
  ) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }
    const auth = req.headers['authorization'] as string | undefined;
    const resp = await this.uploader.uploadSingle(file, auth);
    return { ...resp.data, alt: body.alt, title: body.title, uploadedBy: user.id };
  }

  @Post('images')
  @ApiOperation({ summary: '批量上传图片' })
  @ApiConsumes('multipart/form-data')
  @ApiResponse({ status: 200, description: '图片批量上传成功' })
  @UseInterceptors(FilesInterceptor('files', 10))
  @Roles('admin', 'editor', 'author')
  async uploadImages(
    @UploadedFiles() files: Express.Multer.File[],
    @CurrentUser() user: any,
    @Req() req: Request
  ) {
    if (!files || files.length === 0) {
      throw new BadRequestException('请选择要上传的文件');
    }
    const auth = req.headers['authorization'] as string | undefined;
    const resp = await this.uploader.uploadMultiple(files, auth);
    return resp.data;
  }

  @Post('file')
  @ApiOperation({ summary: '上传文件' })
  @ApiConsumes('multipart/form-data')
  @ApiResponse({ status: 200, description: '文件上传成功' })
  @UseInterceptors(FileInterceptor('file'))
  @Roles('admin', 'editor', 'author')
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Body() body: { description?: string; category?: string },
    @CurrentUser() user: any,
    @Req() req: Request
  ) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }
    const auth = req.headers['authorization'] as string | undefined;
    const resp = await this.uploader.uploadSingle(file, auth);
    return { ...resp.data, description: body.description, category: body.category, uploadedBy: user.id };
  }

  @Get('media')
  @ApiOperation({ summary: '获取媒体库列表' })
  @ApiResponse({ status: 200, description: '返回媒体库列表' })
  @Roles('admin', 'editor', 'author')
  async getMediaList(@Query() query: MediaQueryDto) {
    // TODO: 获取媒体库文件列表
    return {
      code: 200,
      data: {
        files: [],
        pagination: {
          page: query.page,
          limit: query.limit,
          total: 0,
          totalPages: 0
        },
        stats: {
          totalFiles: 0,
          totalSize: '0MB',
          imageCount: 0,
          videoCount: 0,
          audioCount: 0,
          documentCount: 0
        }
      },
      message: '获取成功'
    };
  }

  @Get('media/:id')
  @ApiOperation({ summary: '获取媒体文件详情' })
  @ApiResponse({ status: 200, description: '返回媒体文件详情' })
  @Roles('admin', 'editor', 'author')
  async getMediaDetail(@Param('id') id: string) {
    // TODO: 获取媒体文件详情
    return {
      code: 200,
      data: null,
      message: '获取成功'
    };
  }

  @Delete('media/:id')
  @ApiOperation({ summary: '删除媒体文件' })
  @ApiResponse({ status: 200, description: '媒体文件删除成功' })
  @Roles('admin', 'editor')
  async deleteMedia(@Param('id') id: string) {
    // TODO: 删除媒体文件（包括文件系统和数据库记录）
    return {
      code: 200,
      data: null,
      message: '删除成功'
    };
  }

  @Get('config')
  @ApiOperation({ summary: '获取上传配置' })
  @ApiResponse({ status: 200, description: '返回上传配置' })
  @Roles('admin', 'editor', 'author')
  async getUploadConfig() {
    // TODO: 获取上传相关配置
    return {
      code: 200,
      data: {
        maxFileSize: 10485760, // 10MB
        maxFiles: 10,
        allowedImageTypes: ['jpg', 'jpeg', 'png', 'gif', 'webp'],
        allowedVideoTypes: ['mp4', 'avi', 'mov', 'wmv'],
        allowedAudioTypes: ['mp3', 'wav', 'ogg'],
        allowedDocumentTypes: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'],
        enableThumbnail: true,
        thumbnailSizes: [
          { width: 150, height: 150, name: 'small' },
          { width: 300, height: 300, name: 'medium' },
          { width: 600, height: 600, name: 'large' }
        ]
      },
      message: '获取成功'
    };
  }

  @Post('config')
  @ApiOperation({ summary: '更新上传配置' })
  @ApiResponse({ status: 200, description: '配置更新成功' })
  @Roles('admin')
  async updateUploadConfig(@Body() configDto: UploadConfigDto) {
    // TODO: 更新上传配置
    return {
      code: 200,
      data: null,
      message: '配置更新成功'
    };
  }

  @Post('url')
  @ApiOperation({ summary: '通过URL上传文件' })
  @ApiResponse({ status: 200, description: '文件上传成功' })
  @Roles('admin', 'editor', 'author')
  async uploadFromUrl(
    @Body() body: { 
      url: string; 
      filename?: string; 
      alt?: string; 
      title?: string 
    },
    @CurrentUser() user: any
  ) {
    // TODO: 从URL下载并保存文件
    return {
      code: 200,
      data: {
        id: 1,
        filename: body.filename || 'downloaded_file',
        url: '/uploads/files/downloaded_file.jpg',
        originalUrl: body.url,
        size: 0,
        alt: body.alt,
        title: body.title,
        uploadedBy: user.id,
        uploadedAt: new Date().toISOString()
      },
      message: '文件上传成功'
    };
  }

  @Get('stats')
  @ApiOperation({ summary: '获取上传统计' })
  @ApiResponse({ status: 200, description: '返回上传统计信息' })
  @Roles('admin', 'editor')
  async getUploadStats() {
    // TODO: 获取上传统计信息
    return {
      code: 200,
      data: {
        totalFiles: 0,
        totalSize: '0MB',
        todayUploads: 0,
        weekUploads: 0,
        monthUploads: 0,
        fileTypes: {
          images: 0,
          videos: 0,
          audios: 0,
          documents: 0,
          others: 0
        },
        largestFiles: [],
        recentUploads: [],
        storageUsage: {
          used: '0MB',
          available: '1000MB',
          percentage: '0%'
        }
      },
      message: '获取成功'
    };
  }
}
